package com.wu.store.service.impl;

import com.wu.store.dao.CartDao;
import com.wu.store.entity.Cart;
import com.wu.store.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {
	@Autowired
	private CartDao cartDao;

	@Override
	public int count(Long uid) {
		return cartDao.list(uid).size();
	}

	@Override
	public List<Cart> list(Long uid) {
		return cartDao.list(uid);
	}

	@Override
	public void save(Cart cart) throws Exception {
		Cart oldCart = cartDao.selectById(cart);
		if (oldCart != null) {
			cart.setId(oldCart.getId());
			cart.setUid(oldCart.getUid());
		}
		if (cart.getId() == null) {
			cart.setCreateTime(new Date());
			cartDao.add(cart);
		} else {
			cart.setUpdateTime(new Date());
			int affectedRow = cartDao.update(cart);
			if (affectedRow == 0) {
				throw new Exception("更新失败");
			}
		}
	}

	@Override
	public boolean delete(Cart cart) throws Exception {
		int affectedRow = cartDao.delete(cart);
		if (affectedRow == 0) {
			throw new Exception("删除失败");
		}
		return true;
	}

	@Override
	public boolean batchDelete(Long uid, List<Long> idList) throws Exception {
		int affectedRow = cartDao.batchDelete(uid, idList);
		if (affectedRow == 0) {
			throw new Exception("删除失败");
		}
		return true;
	}
}
